package com.orgcent.tuangou.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.text.TextUtils;
import android.webkit.URLUtil;

/**
 * http 工具类
 */
public class HttpUtil {
	
	public static String toUrl(String srcUrl,HashMap<String,Object> args) {
		StringBuilder urlBuilder = new StringBuilder(srcUrl);
		if (null != args) {
			int size = args.size();
			if (size > 0) {
				urlBuilder.append("?");
			}
			for (Map.Entry<String, Object> entry : args.entrySet()) {
				urlBuilder.append(entry.getKey()).append("=").append(
						entry.getValue()).append("&");
			}
		}
		return urlBuilder.toString();
	}
	
	/**
	 * 判断网络是否有连接
	 * */
	public static Boolean isNetworkAvailable(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = (cm == null ? null : cm.getActiveNetworkInfo());

		if (info == null || !info.isConnected()) {
			return false;
		} else if (info.isRoaming()) {
			return true;
		}
		return true;
	}

	public static abstract class ProgressUpdate {
		public boolean isCanneled; //是否取消下载
		public abstract void doUpdateProgress(int length, int total);
	}

	/**
	 * 从网络获取文件
	 * @param url
	 * @param callback
	 * @return
	 */
	public static File getFileByUrl(File file,String url) {
		if (!URLUtil.isNetworkUrl(url)) {
			return null;
		}

		InputStream instream = null;
		FileOutputStream fos = null;
		try {
			URL myURL = new URL(url);
			URLConnection conn = myURL.openConnection();
			conn.setConnectTimeout(15000);
			conn.setReadTimeout(35000);
			/* 创建连接 */
			conn.connect();
			instream = conn.getInputStream();
			//创建父目录
			File dir = file.getParentFile();
			if(null != dir && !dir.exists()) {
				dir.mkdirs();
			}
			dir.createNewFile();
			
			fos = new FileOutputStream(file);
			
			// 获取网络文件大小
			int size = (int) conn.getContentLength();
			if (size < 0) {
				size = 4096;
			}
			//下载文件
			byte[] tmp = new byte[4096];
			int l;
			while ((l = instream.read(tmp)) != -1) {
				fos.write(tmp, 0, l);
				fos.flush();
			}
			fos.flush();
			return file;
		} catch (Exception e) {
			return null;
		} finally {
			if(null != instream) {
				try {
					instream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(null != fos) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static Bitmap getImageByURL(String uri) {
		HttpClient client = new DefaultHttpClient();
		HttpResponse resp;
		HttpParams params = client.getParams(); // 超时时间
		HttpConnectionParams.setConnectionTimeout(params, 15000);// Set the
		 HttpConnectionParams.setSoTimeout(params, 35000);

		try {
			uri = Uri.encode(uri, ":/"); // 对path编码
			resp = client.execute(new HttpGet(uri));
			BufferedHttpEntity entity = new BufferedHttpEntity(resp.getEntity());

			// BitmapFactory.Options opts = new BitmapFactory.Options();
			// opts.outHeight = 60;
			// opts.outWidth = 60;
			// opts.inSampleSize = 2;
			// return BitmapFactory.decodeStream(entity.getContent(), null,
			// opts);
			return BitmapFactory.decodeStream(entity.getContent());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			client.getConnectionManager().shutdown();
		}
		return null;
	}
}
